<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\model\ClientAccountModel;
use app\model\ClientCashRateModel;
use app\model\CrontabTaskModel;
use app\service\BaseService;
use app\service\CrontabTaskService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

/*
 * 缓存客户日比例
 */

class CacheClientCashRateWork extends BaseWork implements DailyStatWork
{
    public ?int $tag = null;

    public function setTag($tag = null): bool
    {
        if (! is_null($tag)) {
            $this->tag = $tag;
        }
        return true;
    }

    public function getTag(): ?string
    {
        return strval($this->tag);
    }

    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('cache_client_cash_rate_work');
        // 设置参数
        $this->setDescription('缓存客户素材现金比例')
            ->addArgument('media_id', Argument::REQUIRED, '媒体id')
            ->addArgument('type', Argument::REQUIRED, '类型  1：昨日 2：自定义时间 3:今日')
            ->addArgument('date', Argument::OPTIONAL, '日期 Ymd')
            ->setHelp('php think cache_client_cash_rate_work [media_id] [type] [date]');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $mediaId = $input->getArgument('media_id');
        $type = $input->getArgument('type');
        $dateInt = $input->getArgument('date');
        $this->setTag(intval($mediaId));
        // 默认昨日
        if ($type == 1) {
            $dateInt = date('Ymd', strtotime('-1 day'));
            // 获取凌晨的时间戳
            $time = strtotime(date('Y-m-d 00:00:00'));
            // 如果已执行，就不跑了
            if ($this->getCrontabTaskInfo()->finish_time > $time) {
                exit;
            }
            $isOk = CrontabTaskModel::where('task_name', 'media_cost_pull_work')
                ->where('tag', $mediaId . '-1')
                ->where('finish_time', '>', $time)
                ->find();
            if (! $isOk) {
                exit;
            }
            //            $isDone = TaskAccountService::isTodayTaskDone(ServiceCostEnum::TASK_TYPE_ACCOUNT, $mediaId, intval($dateInt));
            //            if (! $isDone) {
            //                exit;
            //            }
        } elseif ($type == 3) {
            // 当日
            $dateInt = date('Ymd');
        }
        $output->writeln('=======缓存素材现金比例开始' . date('Y-m-d H:i:s', time()) . '=======');
        $res = $this->setCashRate((int) $dateInt, (int) $mediaId);
        if ($type == 1 && $res) {
            // 更新任务状态
            CrontabTaskService::setSingleTask($this);
        }
        $output->writeln('=======缓存素材现金比例结束' . date('Y-m-d H:i:s', time()) . '=======');
    }

    private function setCashRate(int $date, int $mediaId)
    {
        // 先更新下当月客户比数据
        Db::startTrans();
        try {
            // 查询所有客户
            $clientIds = ClientAccountModel::where('company_id', 1)
                ->where('media_id', $mediaId)
                ->group('client_id')
                ->column('client_id');
            if (! empty($clientIds)) {
                foreach ($clientIds as $clientId) {
                    // 查询客户消耗
                    $allCost = BaseService::getClientCost($clientId, $mediaId, $date);
                    if ($allCost['cost'] > 0 && $allCost['cash_cost'] > 0) {
                        // 比例 = 现金 / 显帐
                        $valueRate = round($allCost['cash_cost'] / $allCost['cost'], 3);
                        $isHas = ClientCashRateModel::where('date_time', $date)
                            ->where('client_id', $clientId)
                            ->where('media_id', $mediaId)
                            ->find();
                        $data = [
                            'client_id' => $clientId,
                            'media_id' => $mediaId,
                            'date_time' => $date,
                            'valid_rate' => $valueRate,
                            'cash_cost' => $allCost['cash_cost'],
                            'cost' => $allCost['cost'],
                            'create_time' => time(),
                            'update_time' => time(),
                        ];
                        if (! $isHas) {
                            ClientCashRateModel::create($data);
                        } else {
                            ClientCashRateModel::where('id', $isHas['id'])->update($data);
                        }
                    }
                    echo $date . '客户' . $clientId . '完成' . PHP_EOL;
                }
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return self::setError($e->getMessage());
        }
    }
}
